package com.fangyahao.role.service.impl;

import com.fangyahao.role.bean.RoleBean;
import com.fangyahao.role.bean.UserBean;
import com.fangyahao.role.dao.RoleDao;
import com.fangyahao.role.dao.UserDao;
import com.fangyahao.role.service.RoleService;
import com.fangyahao.role.utils.DaoFactory;

import java.util.List;

public class RoleServiceImpl implements RoleService {

    private RoleDao dao;

    @Override
    public int insertRole(String name) {
        DaoFactory<RoleDao> daoFactory =new DaoFactory<>();
        dao=daoFactory.getDaoTransaction(RoleDao.class);
        RoleBean roleBean = new RoleBean();
        roleBean.setName(name);

        if(dao.findRoleUser(roleBean)!=null){
            return -1;
        }

        return dao.insertRole(name);
    }

    @Override
    public int deleteRoleById(Integer id) {
        DaoFactory<RoleDao> daoFactory =new DaoFactory<>();
        dao=daoFactory.getDaoTransaction(RoleDao.class);
        RoleBean roleBean = new RoleBean();
        roleBean.setId(id);

        RoleBean role = dao.findRoleUser(roleBean);

        if(role!=null&&role.getUserEntityList().isEmpty()){
            return dao.deleteRoleById(id);
        }

        return -1;
    }

    @Override
    public int updateRoleNameByName(String name, String newName) {
        DaoFactory<RoleDao> daoFactory =new DaoFactory<>();
        dao=daoFactory.getDaoTransaction(RoleDao.class);

        RoleBean roleBean = new RoleBean();
        roleBean.setName(newName);
        if(dao.findRoleUser(roleBean)!=null){
            return -1;
        }


        return dao.updateRoleNameByName(name,newName);
    }

    @Override
    public List<RoleBean> findAllRole() {
        DaoFactory<RoleDao> daoFactory =new DaoFactory<>();
        dao=daoFactory.getDao(RoleDao.class);

        return dao.findAllRole();
    }

    @Override
    public boolean isHavePermissions(Integer userId) {
        boolean flag = false;
        DaoFactory<RoleDao> roleDaoFactory =new DaoFactory<>();
        dao=roleDaoFactory.getDao(RoleDao.class);

        UserBean userBean = new UserBean();
        userBean.setId(userId);
        DaoFactory<UserDao> userDaoFactory = new DaoFactory<>();
        UserDao userDao =userDaoFactory.getDao(UserDao.class);
        UserBean user = userDao.selectUser(userBean);
        List<String> roleList = user.getRoleList();
        RoleBean roleBean = new RoleBean();
        for(String roleName : roleList){
            roleBean.setName(roleName);
            RoleBean role = dao.findPermission(roleBean);
            List<String> permissions = role.getPermission();
            for(String permission : permissions){
                if(permission.contains("/fangyahao/role")){
                    flag=true;
                    break;
                }
            }

        }

        return flag;
    }


}
